import os,re
import sys
import subprocess
import argparse
import signal
import sys
import time, sys
import datetime
import webbrowser
import platform

def runadbcommand(command, shell_val=True):
    try:
        info = subprocess.Popen(command, stdout= subprocess.PIPE, stderr=subprocess.STDOUT, shell=shell_val)
        print info.stdout.read()
    except subprocess.CalledProcessError:
        print "Subprocess called error" # handle errors in the called executable
    except OSError:
        print "os error" # executable not found
        
def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"
    
def run_sysmon_profiler(real_subsystem,build_location,filestore):    
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d-%H-%M-%S')
    adb_wait = "adb wait-for-device"
    adb_root = "adb wait-for-device root"
    disable_verity = "adb wait-for-device disable-verity"
    remount = "adb wait-for-device remount"
    runprofiler = "adb shell /data/sysMonApp profiler --q6"
    runprofiler = runprofiler + " " + real_subsystem
    runprofilerle = "adb shell /usr/bin/sysMonAppLE profiler --q6"
    runprofilerle = runprofilerle + " " + real_subsystem    
    pushsysmonapp = "adb wait-for-device push " + build_location + "/sysmonapp/sysMonApp /data/"
    pushsysmonapple = "adb wait-for-device push " + build_location + "/sysmonapp/sysMonAppLE /usr/bin/"
    meta = "adb wait-for-device shell cat /firmware/verinfo/ver_info.txt > " + filestore + "/ImageInfo.txt"
    imagefile = filestore + "//ImageInfo.txt"
    sysmonapppexe = "adb shell chmod 777 /data/sysMonApp"
    sysmonapppexele = "adb shell chmod 777 /usr/bin/sysMonAppLE"
    if real_subsystem == "adsp":
       sysmonbinpull = "adb pull /sdcard/sysmon.bin" + " " + filestore
       binfilename = filestore + "/sysmon.bin"
       runparser = build_location + "/tools/HTMLParser/sysmon_parser.exe" + " " + filestore + "/sysmon.bin --outdir" + " " +  filestore
    else:
       sysmonbinpull = "adb pull /sdcard/sysmon_" + real_subsystem + ".bin" + " " + filestore
       binfilename = filestore + "/sysmon_" + real_subsystem + ".bin"
       runparser = build_location + "/tools/HTMLParser/sysmon_parser.exe" + " " + filestore + "/sysmon_" + real_subsystem + ".bin --outdir" + " " +  filestore
    pushshfile = "adb wait-for-device push " + build_location + "\\sysmonapp\\RunProfiler.sh /data/"
    runparser = runparser + "/sysmon_report" + st
    foldername = filestore + "/sysmon_report" + st + "/sysmon_report.html"
    os.system(meta)
    text_file = open(imagefile,'r')    
    for line in text_file:
        if 'apps' in line and 'LA' in line:
            LAFlag = 1
        if 'apps' in line and 'LE' in line:
            LAFlag = 0
    runadbcommand(adb_root)
    runadbcommand(adb_wait)
    runadbcommand(adb_root)
    runadbcommand(remount)
    runadbcommand(meta)
    if LAFlag == 1:
       runadbcommand(pushsysmonapp)
       runadbcommand(sysmonapppexe) 
       runprofileros=runprofiler
    elif LAFlag == 0:
       runadbcommand(pushsysmonapple)
       runadbcommand(sysmonapppexele)
       runprofileros=runprofilerle
    try:
        os.system(runprofileros)
    except KeyboardInterrupt:
        print "\n"
    os.system(sysmonbinpull)
    print "-----Running Parser-----"
    if os.path.exists(binfilename):
        os.system(runparser)    
        webbrowser.open(foldername)
        print "The parser files are located at:", foldername
    else:
       print"Input file does not Exist:", binfilename
       print"*****Error*****"
    print "-----Done !!!-----"
      
def main():
    real_subsystem = 0;
    if args == 1:
       filestore = "C:\\Temp"
       if not os.path.isdir(filestore):
          os.makedirs(filestore)       
    else:
       parser = argparse.ArgumentParser()       
       parser.add_argument( '--outdir', '-o',  dest='OutputFolder_Path', help='python runSysMonProfiler.py->Output path is C:\Temp python runSysMonProfiler.py -o <output folder>')
       parser.add_argument( '--q6', '-q6',  dest='q6_subsystem', help='python runSysMonProfiler.py -q6 <adsp/cdsp/sdsp>')
       options = parser.parse_args()
       real_subsystem = str(options.q6_subsystem)
       filestore = str(options.OutputFolder_Path)
       if filestore == "None":
          filestore = "C:\\Temp"
          if not os.path.isdir(filestore):
             os.makedirs(filestore)          
       else:      
          if not os.path.isdir(filestore):
             os.makedirs(filestore)
    build_location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if real_subsystem == "None" or real_subsystem == 0:
       opsytem=platform.system()  
       if opsytem == 'Windows':
           subsystem=build_location.split("\\")
       else:
           subsystem=build_location.split("/")
       subsystem_len=len(subsystem)
       subsystem=subsystem[subsystem_len-2]
       subsystem=subsystem.split("_")
       real_subsystem = subsystem[0]
    print "Q6 Subsystem that is getting profiled is:", real_subsystem
    Flag = run_sysmon_profiler(real_subsystem,build_location,filestore)

if __name__ == '__main__':
    args=len(sys.argv)   
    main()
